package com.justnow.solution;

public class Solution02 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode listNode = reverseBetween(node1, 2, 4);

    }

    public static ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null) {
            return head;
        }
        int distance = n - m;
        ListNode leftNode = head;

        while (m > 2 && leftNode != null) {
            leftNode = leftNode.next;
            m--;
        }

        ListNode pre = null;
        ListNode current = leftNode.next;
        ListNode rightNode = current;
        while (distance > 0 && current != null) {
            ListNode temp = current.next;
            pre = current;
            current = temp;
            distance--;
        }


        rightNode.next = current;
        leftNode.next = pre;

        return head;
    }
}

class ListNode {
    int val;
    ListNode next;
    public ListNode(int val) {
        this.val = val;
    }
}
